import axios, { AxiosError, type AxiosInstance, type AxiosRequestConfig, type AxiosResponse} from 'axios'

import adapter from 'axios-miniprogram-adapter'

// import { ElMessage } from 'element-plus';
import type {Request } from './types';

// const request = axios.create({
//     // 运行到浏览器时，把这一行注释回来，VUE_APP_BASE_API是在vue.config.js中配置的，官网有
//     // baseURL: process.env.VUE_APP_BASE_API,
//     // 运行到浏览器时下面一行注释掉
//     baseURL: import.meta.env.VITE_BASE_URL,
//     // 在微信开发者工具环境中，axios，http是发不出去的，没有跨域，vue.config.js文件也是无效的
//     // 基于axios-miniprogram-adapter包给axios中添加一个适配器
//     // 运行到浏览器时，下面一行注释掉，axios时可以在浏览器中正常使用的，不需要适配器
//     adapter: adapter,
// })
const defaultConfig:AxiosRequestConfig={
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: import.meta.env.VITE_REQUEST_TIME_OUT,
    // withCredentials: true,
    responseType:"json",
    transformRequest:[
        (data) =>{
            data = JSON.stringify(data);
            return data;
        }
    ],
    validateStatus(){
        return true;
    },
    transformResponse:[
        (data) =>{
            if(typeof data  === "string" && data.startsWith("{")){
                data = JSON.parse(data);
            }
            console.log(data)
            return data;
        },
    ],
    headers: {
        // Accept: "application/json, text/plain, */*",
        "Content-Type": "application/json",
        // "X-Requested-With": "XMLHttpRequest",
    }
}

  /**
   * Axios create的时候后去的配置参数
   * @param config
   */
const getConfig = (config?: AxiosRequestConfig): AxiosRequestConfig => {
    if (!config) return defaultConfig;
    return defaultConfig;
  };

class httpRequest{
    constructor(){
        this.httpInterceptorsRequest();
        this.httpInterceptorsResponse();
    }
    private static axiosInstance : AxiosInstance = axios.create(getConfig());

    private httpInterceptorsRequest():void{
        httpRequest.axiosInstance.interceptors.request.use(
            (config:AxiosRequestConfig)=>{
                // 定义一个变量来存储token
                let token = null;
                
                // 调用uni.getStorage API
                uni.getStorage({
                  // 设置键名为token
                  key: 'token',
                  // 设置成功回调
                  success: function (res) {
                    // 将返回的数据赋值给token
                    token = res.data;
                    // 打印token的值
                    console.log(token);
                  },
                  // 设置失败回调
                  fail: function (err) {
                    // 打印错误信息
                    console.error(err);
                  }
                });

                if(token&&config.headers){
                    // config.headers.Authorization = token
                    typeof config.headers.set ==='function'&&
                    config.headers.set("token",token)
                }
                return config
            },
            (err)=>{
                console.log(err);
                return Promise.reject(err);
            }
        )
    }
    private httpInterceptorsResponse():void{
        httpRequest.axiosInstance.interceptors.response.use(
            (response:AxiosResponse)=>{
                console.log("response:"+response)
                const res = response.data
                if(response.status!=200){
                    uni.showLoading({
                        message:'请求错误',
                        type:'error',
                        duration:5*500,
                    })
                    return res
                }
                if(res.code===200){
                    return res
                }
                if(res.code!=200){
                    uni.showLoading({
                        message:res.msg,
                        type:'error',
                        duration:5*500,
                    })
                    return res
                }
            },(error:AxiosError)=>{
                console.log('err',error);
                uni.showLoading({
                    message:error.message,
                    type:'error',
                    duration:5*500
                })
                return Promise.reject(error)
            }
        )
    }

    public reqGet: Request = async(
        url:string,
        params?:unknown,
        config?:AxiosRequestConfig
    )=>{
        return await httpRequest.axiosInstance.get(url,{params,...config})
    }
    public reqPost:Request = async (
        url: string,
        params:unknown = {},
        config?: AxiosRequestConfig
    )=>{
        return await httpRequest.axiosInstance.post(url,params,config)
    }

    public get:Request = async(
        url:string,
        params?:unknown,
        config?:AxiosRequestConfig
    )=>{
        return await axios.get(url,{params,...config})
    }

    public post:Request = async(
        url: string,
        params:unknown = {},
        config?: AxiosRequestConfig
    )=>{
        return await axios.post(url,{params},config)
    }

}
export default httpRequest